import { useRequest } from "@/hooks/use-request";
import { useUserStore } from "@/stores/global/user";
import { antdUtils } from "@/utils/antd";
import { t } from "@/utils/i18n";
import { CheckOutlined, CloseOutlined, PlusOutlined } from "@ant-design/icons";
import { useMount } from "ahooks";
import {
  Button,
  Col,
  DatePicker,
  Form,
  Input,
  Modal,
  Popover,
  Row,
  Space,
  Switch,
  Timeline,
} from "antd";
import dayjs from "dayjs";
import { useState } from "react";
import { useParams } from "react-router-dom";
import projectService from "../service";

const ProjectTimeNode = () => {
  const dateFormat = "YYYY-MM-DD";
  const { currentUser } = useUserStore();
  const params = useParams();
  const [showAddModl, setShowAddModl] = useState(false);
  const [projectData, setProjectData] = useState<any>({});
  const [newPlanForm] = Form.useForm();
  const [isFilter, setIsFilter] = useState(true);
  const { runAsync: findPriject } = useRequest(projectService.findPriject, {
    manual: true,
  });

  const { runAsync: addTimeNode } = useRequest(projectService.addTimeNode, {
    manual: true,
  });

  const { runAsync: deleteTimeNode } = useRequest(
    projectService.deleteTimeNode,
    {
      manual: true,
    }
  );

  useMount(() => {
    getData();
  });

  const getData = async () => {
    const [error, data] = await findPriject(params.id ? params.id : "");

    if (error) {
      antdUtils.message?.error(error);
      return;
    }
    setProjectData(data);
  };

  const newTimeNode = async (value: any) => {
    const [error, data] = await addTimeNode({
      id: projectData.id,
      info: value.info,
      time: dayjs(value.time).format(dateFormat),
      operator: `${currentUser?.id}__${currentUser?.nickName}`,
    });
    if (error) {
      antdUtils.message?.error("添加失败");
      return;
    }
    setShowAddModl(false);
    setProjectData(data);
  };

  const deleteNode = async (ban: any) => {
    const [error, data] = await deleteTimeNode(ban);
    if (error) {
      antdUtils.message?.error("删除失败");
      return;
    }
    setProjectData(data);
  };

  return (
    <div className=" w-1/1 h-1/1">
      <Row align="middle">
        <Col>{`项目: ${projectData.name ? projectData.name : ""}`}</Col>
        <Col offset={1}>
          <Button
            type="primary"
            onClick={() => {
              setShowAddModl(true);
            }}
            icon={<PlusOutlined />}
          >
            {t("VjwnJLPY") /** 新建 */}
          </Button>
        </Col>
        <Col offset={1}>
          <Space>
            <Switch
              checkedChildren={<CheckOutlined />}
              unCheckedChildren={<CloseOutlined />}
              defaultChecked={isFilter}
              onChange={(checked: boolean) => {
                setIsFilter(checked);
              }}
            />
            <div>过滤已删除记录</div>
          </Space>
        </Col>
      </Row>
      <br />
      <Timeline
        className=" w-[100%] h-[90%] overflow-y-auto overflow-x-hidden pt-[20px] pr-[20px]"
        mode="left"
        items={
          projectData.timeNode
            ? (isFilter
                ? JSON.parse(projectData.timeNode).filter((item: any) => {
                    return item.state === "0" || item.state === undefined;
                  })
                : JSON.parse(projectData.timeNode)
              )
                .sort((a: any, b: any) => {
                  return b.time > a.time ? -1 : 1;
                })
                .map((item: any) => {
                  return item.state === "0" || item.state === undefined
                    ? {
                        label: (
                          <Popover
                            placement="topRight"
                            content={
                              <Button
                                size="small"
                                onClick={() => {
                                  deleteNode({
                                    id: item.id,
                                    pid: projectData.id,
                                    uid: currentUser?.id,
                                    nicKName: currentUser?.nickName,
                                  });
                                }}
                                danger
                              >
                                {t("HJYhipnp") /**删除 */}
                              </Button>
                            }
                          >
                            <p className=" text-[rgb(22, 119, 255)]">{`${
                              item.time
                            }--${item.operator.split("__")[1]}`}</p>
                          </Popover>
                        ),
                        children: <p>{item.info}</p>,
                      }
                    : {
                        label: (
                          <Popover
                            placement="topRight"
                            trigger="hover"
                            content={
                              <p>{`刪除人 ${item.deleteTime}--${
                                item.deleteOperator.split("__")[1]
                              }`}</p>
                            }
                          >
                            <p className=" text-[red]">{`${item.time}--${
                              item.operator.split("__")[1]
                            }`}</p>
                          </Popover>
                        ),
                        children: <p className="text-[red]">{item.info}</p>,
                      };
                })
            : []
        }
      />

      <Modal
        title="添加节点"
        open={showAddModl}
        afterClose={() => {
          newPlanForm.resetFields();
        }}
        destroyOnClose={true}
        footer={null}
        onCancel={() => {
          setShowAddModl(false);
        }}
      >
        <Form
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 17 }}
          form={newPlanForm}
          name="newPlan"
          onFinish={newTimeNode}
        >
          <Form.Item name="info" label="节点" rules={[{ required: true }]}>
            <Input.TextArea autoSize={{ minRows: 2, maxRows: 10 }} />
          </Form.Item>
          <Form.Item name="time" label="时间" rules={[{ required: true }]}>
            <DatePicker format={dateFormat} />
          </Form.Item>
          <Form.Item
            style={{ marginTop: "3.125vw" }}
            wrapperCol={{ span: 16, offset: 4 }}
            shouldUpdate
          >
            {() => (
              <Button
                type="primary"
                htmlType="submit"
                style={{ width: "100%" }}
              >
                {t("confirm") /**确认 */}
              </Button>
            )}
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ProjectTimeNode;
